using BackOffice.Application.DTOs;
using BackOffice.Application.Services;
using Backoffice.Application.Common;
using Backoffice.Domain.Entities.App;
using System.Linq;
using System.Threading.Tasks;
using Backoffice.Domain.Repositories;
using Microsoft.EntityFrameworkCore;

namespace BackOffice.Application.Services
{
    public class ArticleService : IArticleService
    {
        private readonly IRepository<AppArticle> _articleRepo;

        public ArticleService(IRepository<AppArticle> articleRepo)
        {
            _articleRepo = articleRepo;
        }

        public async Task<ApiResult> CreateArticleAsync(CreateOrUpdateArticleDto dto)
        {
            var exists = (await _articleRepo.GetAllAsync())
                          .Any(a => a.Title == dto.Title);
            if (exists)
                return ApiResult.Fail("标题已存在", 3001);

            // 根据DTO中的Status字段设置文章状态
            var status = dto.Status.HasValue ? (ArticleStatus)dto.Status.Value : ArticleStatus.Draft;
            var article = new AppArticle(dto.Title, dto.Content, dto.Category, dto.Tags, status);
            await _articleRepo.CreateAsync(article);
            return ApiResult.Success(article, "创建成功");
        }

        public async Task<ApiResult> UpdateArticleAsync(Guid id, CreateOrUpdateArticleDto dto)
        {
            var article = await _articleRepo.GetByIdAsync(id);
            if (article == null) return ApiResult.Fail("文章不存在", 3002);

            article.UpdateInfo(dto.Title, dto.Content, dto.Category, dto.Tags);
            
            // 如果DTO中指定了状态，则更新状态
            if (dto.Status.HasValue)
            {
                article.ChangeStatus((ArticleStatus)dto.Status.Value);
            }
            
            await _articleRepo.UpdateAsync(article);
            return ApiResult.Success(article, "更新成功");
        }

        public async Task<ApiResult> DeleteArticleAsync(Guid id)
        {
            var article = await _articleRepo.GetByIdAsync(id);
            if (article == null) return ApiResult.Fail("文章不存在", 3002);

            await _articleRepo.DeleteAsync(article.Id);
            return ApiResult.Success(null, "删除成功");
        }

        public async Task<ApiResult> ChangeStatusAsync(Guid id, ArticleStatus newStatus)
        {
            var article = await _articleRepo.GetByIdAsync(id);
            if (article == null) return ApiResult.Fail("文章不存在", 3002);

            article.ChangeStatus(newStatus);
            await _articleRepo.UpdateAsync(article);
            return ApiResult.Success(article, "状态已更新");
        }

        public async Task<ApiResult> GetArticleListAsync()
        {
            var list = await _articleRepo.GetAllAsync();
            return ApiResult.Success(list.OrderByDescending(a => a.CreatedAt), "获取成功");
        }
        
        public async Task<ApiResult> SearchArticlesAsync(ArticleSearchDto dto)
        {
            var query = _articleRepo.Query();
            if (!string.IsNullOrEmpty(dto.Title))
                query = query.Where(a => a.Title.Contains(dto.Title));
            if (!string.IsNullOrEmpty(dto.Category))
                query = query.Where(a => a.Category == dto.Category);
            if (!string.IsNullOrEmpty(dto.Tags))
                query = query.Where(a => a.Tags != null && a.Tags.Contains(dto.Tags));
            if (dto.Status.HasValue)
                query = query.Where(a => (int)a.Status == dto.Status.Value);
            if (dto.CreatedFrom.HasValue)
                query = query.Where(a => a.CreatedAt >= dto.CreatedFrom.Value);
            if (dto.CreatedTo.HasValue)
                query = query.Where(a => a.CreatedAt <= dto.CreatedTo.Value);
            var result = await query.ToListAsync();
            return ApiResult.Success(result);
        }
    }
}